package com.freshmarket.freshmarket.controller;


import com.freshmarket.freshmarket.controller.form.FormKillProduct;
import com.freshmarket.freshmarket.service.ILimitedTimeOfferService;
import com.freshmarket.freshmarket.utils.Result;
import com.freshmarket.freshmarket.utils.ValidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotEmpty;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Squirrel
 * @since 2020-09-04
 */
@RestController
@RequestMapping("/freshmarket/limited-time-offer")
public class LimitedTimeOfferController {

    @Autowired
    private ILimitedTimeOfferService limitedTimeOfferService;

    /**
     * 查询商品的所有类别
     * @return
     */
    @GetMapping("findNames")
    public Result findNames(){

        return Result.successResult(limitedTimeOfferService.findNames());
    }

    /**
     * 根据类型id 查询正常的商品
     * @param id
     * @return
     */
    @GetMapping("findByProductTypeId")
    public Result findByProductTypeId(int id){

        return Result.successResult(limitedTimeOfferService.findByProductTypeId(id));
    }
    /**
     *  查询是否超过库存数量
     * @param id
     * @return
     */
    @GetMapping("numbers")
    public Result numbers(int id,int numbers) {

        return Result.successResult(limitedTimeOfferService.findByIdNum(id,numbers));
    }

    /**
     * 添加秒杀商品
     * @param formKillProduct
     * @param result
     * @return
     */
   @PostMapping("registerKillProduct")
    public Result registerKillProduct(@RequestBody @Valid FormKillProduct formKillProduct, BindingResult result){
        String extract = ValidUtil.extract(result);
       if(extract==null){
           @Future Date date = formKillProduct.getDate();
           long time=(date.getTime()-60*60*8*1000);
           date.setTime(time);
           SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           String string = format.format(date);
           formKillProduct.setNewDate(string);
           return Result.successResult(limitedTimeOfferService.addKillProduct(formKillProduct));
       }
       return Result.successResult(extract);
   }

   @GetMapping("findAll")
    public Result findAll(){
       return Result.successResult(limitedTimeOfferService.findAll());
   }
}

